package com.vates.login.services.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vates.login.model.Role;
import com.vates.login.model.User;
import com.vates.login.services.SecurityService;
import com.vates.login.services.UserService;
import com.vates.login.services.security.CustomUserDetails;
import com.vates.login.services.security.UserGrantedAuthority;

@Service("securityService")
public class SecurityServiceImpl implements SecurityService {

	@Autowired
	private UserService userService;
	
	@Autowired
	@Qualifier("authenticationManager")
	private AuthenticationManager authenticationManager;
	
	@Override
	@Transactional
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if (username != null && !username.isEmpty()) {
			User user = userService.getUser(username);
			if (user == null) {
				return null;
			}
			
			Iterator<Role> it = user.getRoles().iterator();
			List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
			while (it.hasNext()) {
				String authority = it.next().getAuthority();
				GrantedAuthority grantedAuth = new UserGrantedAuthority(authority);
				grantedAuthorities.add(grantedAuth);
			}

			CustomUserDetails cu = new CustomUserDetails(user.getId(), user.getUsername(), user.getPasswd(),
					grantedAuthorities.toArray(new GrantedAuthority[] {}), user.isIsActive());
			return cu;
		} else {
			return null;
		}
	}

	@Override
	public boolean login(String userName, String password) {
		try {
			Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName, password));
			if (authenticate.isAuthenticated()) {
				SecurityContextHolder.getContext().setAuthentication(authenticate);
				return true;
			}
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
		return false;
	}

}
